<template>
  <view class="fuel_remit_wraper">
    <!-- 头部 -->
    <view class="fuel_remit_nav">
      <view class="title_wraper">
        <view class="title_left">
          <view class="title_name">{{ stationData.stationName }}</view>
          <view class="title_region">{{ stationData.detailRegionData || "" }}</view>
        </view>
        <view class="title_right" @click="openLocation()">
          <view class="icon nav"></view>
          <view class="text">{{ distances }}</view>
        </view>
      </view>
      <view class="main_wraper">
        <view class="main_title"><text class="text">￥</text>{{ selectStaOilGunList.oilStationPrice }}</view>
      </view>
    </view>
    <!-- 优惠劵列表 -->
    <view class="all_coupon_wraper">
      <view class="all_coupon confirm">
        <view class="all_coupon_text">确认订单</view>
      </view>
      <view class="down_coupon">
        <view class="down_coupon_text">油枪</view>
        <view class="down_coupon_val">{{ oilGunNum }}号枪</view>
      </view>
      <view class="down_coupon">
        <view class="down_coupon_text">油品</view>
        <view class="down_coupon_val">{{ oilName }}</view>
      </view>
      <view class="down_coupon">
        <view class="down_coupon_text">金额</view>
        <view class="down_coupon_val">￥{{ priceValue }}</view>
      </view>
    </view>
    <!-- 优惠劵列表 -->
    <view class="all_coupon_wraper">
      <view class="all_coupon">
        <view class="all_coupon_text">合计优惠</view>
        <view class="all_coupon_val">￥{{ NewCouponPrice }}</view>
      </view>
      <view class="down_coupon">
        <view class="down_coupon_text">立减</view>
        <view class="down_coupon_val">-￥{{ verticalPrice || 0 }}</view>
      </view>
      <view class="coupon_info" @click="clickCoupons((CouponData.couponList || []).length === 0)">
        <view class="coupon_info_main">
          <view class="coupon_left">优惠劵</view>
          <view class="coupon_right" v-if="chosenCoupon !== -1 && coupons.length !== 0 && radioCouponsValue !== '-1'"> - {{ coupons[chosenCoupon].value }} 元 </view>
          <view class="coupon_right" v-else-if="coupons.length === 0">暂无优惠劵可用</view>
          <view class="coupon_right" v-else>{{ coupons.length }}张可用</view>
          <view class="icon_jiantou"></view>
        </view>
      </view>
    </view>
    <!-- 支付方式 -->
    <view class="remit_page_container">
      <view class="remit_page_wraper">
        <view class="remit_page_type">支付方式</view>
        <radio-group @change="(e) => radioChangeRemit(e)">
          <view class="stored_radio">
            <view class="stored_card">
              <view class="icon stored"></view>
              <view class="stored_title">电子卡支付</view>
              <view class="stored_amt">（￥ {{ CouponData.balance || 0 }}）</view>
            </view>
            <radio value="1" :checked="radioParams === '1'" @click="changeStoredVale()" />
          </view>
          <view class="divider_line"></view>
          <view class="stored_radio">
            <view class="stored_card">
              <view class="icon vx"></view>
              <view class="stored_title">微信支付</view>
            </view>
            <radio value="2" :checked="radioParams === '2'" />
          </view>
        </radio-group>
      </view>
    </view>
    <!-- 优惠劵弹窗 -->
    <uni-popup mask-click="true" ref="popupRefCoupon" type="bottom" background-color="#fff" @maskClick="$refs.popupRefCoupon.close(), (showCouponList = false)">
      <view class="coupons_popup_container">
        <view class="title">优惠劵</view>
        <view class="icon_coupons" @click="$refs.popupRefCoupon.close(), (showCouponList = false)"></view>
        <view class="van_popup_main">
          <radio-group @change="(e) => radioChangeCoupons(e)">
            <view class="popup_list" @click.stop="changeRadioCoupon(index + '')" v-for="(item, index) in coupons" :key="item.id">
              <view class="left_popup" :class="[item.couponType === '1' ? '' : 'red']">
                <view class="valueDesc">{{ item.valueDesc }}</view>
                <view class="condition">{{ item.condition }}</view>
              </view>
              <view class="right_popup">
                <view class="name" :class="[item.couponType === '1' ? '' : 'red']">{{ item.name }}</view>
                <view class="time">截止：{{ item.time }}</view>
              </view>

              <view class="radio">
                <radio :value="index + ''" :checked="index + '' === radioCouponsValue" />
              </view>
            </view>
          </radio-group>
        </view>
      </view>
    </uni-popup>
    <!-- 底部支付 -->
    <view class="bottom_fix_bar">
      <view class="car_container">
        <!-- <view class="icon_car" @click="changeCarPop()">
					<view class="num">{{1}}</view>
        </view> -->
        <view class="newPrice">
          <view class="price_bar"
            ><span class="price_value">￥{{ newPrice }}</span></view
          >
          <view class="price_coupon" v-if="!!couponPrice || CouponData.discountAmt > 0"
            >已优惠<span class="coupon_value">￥{{ NewCouponPrice }}</span></view
          >
        </view>
      </view>
      <view @click="submitRemit()" class="button_submit" :class="[(radioParams === '1' && newPrice > CouponData.balance) || priceValue < 0.01 || priceValue > 50000 || !oilGunNum || !oilName ? 'active_button' : '']"> 立即支付</view>
    </view>
  </view>
</template>

<script>
export default {
  head() {
    return {
      title: "一键加油",
    };
  },
  data() {
    return {
      stationData: {},
      radioParams: "2",
      radioCouponsValue: "-1",
      showCouponList: false, // 优惠劵
      oilGunNum: "", // 油枪号
      oilName: "", // 油枪名字
      oilId: "", // 油ID
      priceValue: "", // 价格
      CouponData: {}, // 优惠劵信息
      chosenCoupon: -1, // 优惠劵索引
      couponPrice: "", // 优惠金额
      verticalPrice: "", // 立减
      couponNo: "", // 优惠劵编号
      stationId: "",
      distances: "",
      userInfoFull: {}, // 用户的所有信息
    };
  },

  onLoad(e) {
    console.log(e, "eeee");
    this.stationId = e.stationId;
    this.distances = e.distances;
    this.oilGunNum = e.oilGunNum;
    this.oilName = e.oilName;
    this.oilId = e.oilId;
    this.priceValue = e.priceValue;
    this.init();
  },
  mounted() {
    this.userInfoFull = this.$store.state.user.userInfoFull || {};
    console.log("4444444userInfoFull", this.userInfoFull);
  },
  watch: {},
  computed: {
    coupons() {
      const { couponList = [] } = this.CouponData;
      return couponList.map((item) => {
        // couponType  1现金券2折扣券 couponAmt 优惠金额 newAmtByCoupon: 优惠后的金额 issueName:发放方式名称
        // 如果 couponType 为2时 couponAmt 为折扣百分比 couponThresholdAmt  最低消费金额
        const couponAmt = item.couponType === "1" ? `${item.couponAmt} ￥` : `${item.couponAmt} %`;
        const value = item.couponType === "1" ? `${item.couponAmt}` : `${Number(this.priceValue) / item.couponAmt}`;
        return {
          ...item,
          id: item.couponId,
          condition: `满${item.couponThresholdAmt}元可用`,
          name: item.couponType === "1" ? "立减劵" : "折扣劵",
          time: item.couponEffectiveTime,
          valueDesc: couponAmt,
          value: Number(value).toFixed(2),
        };
      });
    },

    newPrice() {
      if (!!this.couponPrice) {
        return (Number(this.priceValue) - this.couponPrice - this.verticalPrice).toFixed(2);
      }
      return Number(this.priceValue - this.verticalPrice).toFixed(2);
    },
    // 优惠总价格
    NewCouponPrice() {
      if (!!this.couponPrice) {
        return (Number(this.couponPrice) + this.verticalPrice).toFixed(2);
      }
      return (this.verticalPrice || 0).toFixed(2);
    },
    // 展示的油站信息
    selectStaOilGunList() {
      const { oilList = [] } = this.stationData || {};
      return oilList.find((val) => val.oilId == this.oilId) || {};
    },
  },

  methods: {
    async init() {
      this.stationData = JSON.parse(uni.getStorageSync("stationData")) || {};
      this.getPayInfo();
    },

    openLocation() {
      const { stationData } = this;
      let longitude = Number(stationData.stationLongitude).toFixed(0);
      let latitude = Number(stationData.stationLatitude).toFixed(0);
      if (Number(latitude) > 90 || Number(latitude) < -90) {
        latitude = "0";
      }
      if (Number(longitude) > 180 || Number(longitude) < -180) {
        longitude = "0";
      }
      uni.openLocation({
        longitude: Number(longitude),
        latitude: Number(latitude),
        name: stationData.stationName,
        success: function () {
          console.log("success");
        },
        fail: function (e) {
          console.log(e, "fail");
        },
      });
    },

    // 优惠劵选中状态
    radioChangeCoupons(e) {
      this.radioCouponsValue = e.detail.value;
    },

    // 储值卡选中状态
    radioChangeRemit(e) {
      this.radioParams = e.detail.value;
    },

    clickCoupons(status) {
      if (status) {
        return;
      }
      this.$refs.popupRefCoupon.open();
      this.showCouponList = true;
    },

    // 点击优惠劵
    changeRadioCoupon(index) {
      this.chosenCoupon = index;
      this.$refs.popupRefCoupon.close();
      this.showCouponList = false;
      this.radioCouponsValue = index;
      this.couponPrice = Number(this.coupons[index].value).toFixed(2);
      this.couponNo = this.coupons[index].couponNo;
      this.updateOrderByCoupon();
    },

    // 调取优惠劵订单
    async updateOrderByCoupon() {
      const { oilGunNum, phoneNumber, openId, stationId, newPrice, oilId, couponNo } = this;
      const { ordNo } = this.CouponData;
      try {
        const res = await this.$Request({
          url: "/updateOrderByCoupon",
          method: "POST",
          data: {
            aliUserId: "1",
            appType: "1",
            cardFlag: "1",
            gunName: oilGunNum,
            mobilePhone: phoneNumber,
            oilId,
            openId: openId,
            couponNo,
            orderNo: ordNo,
            payType: "wx",
            receivableAmt: newPrice,
            stationId,
            version: "1.0",
          },
        });
        if (res.retCode === 0) {
          this.CouponData = res.data || {};
          this.ordNo = res.data.ordNo;
          this.verticalPrice = res.data.discountAmt || 0;
        } else {
          this.radioParams = "2";
          this.radioCouponsValue = "-1";
          throw new Error("储值卡无法交易");
        }
      } catch (error) {
        uni.showToast({
          title: error,
          icon: "error",
        });
      }
    },
    // 点击储值卡
    changeStoredVale() {
      this.updateOrderByCoupon();
    },

    // 获取订单信息
    async getPayInfo() {
      const { oilGunNum, phoneNumber, openId, stationId, newPrice } = this;
      uni.showLoading({
        title: "获取订单信息",
        mask: true,
      });
      try {
        const res = await this.$Request({
          url: "/createOrder",
          method: "POST",
          data: {
            aliUserId: "1",
            appType: "1",
            cardFlag: "1",
            gunName: oilGunNum,
            mobilePhone: phoneNumber,
            newCreatefalg: "1",
            openId: openId,
            orderOriginType: "2",
            payType: "wx",
            receivableAmt: newPrice,
            stationId,
            version: "1.0",
          },
        });
        if (res.retCode === 0) {
          this.CouponData = res.data || {};
          this.verticalPrice = res.data.discountAmt || 0;
        } else {
          throw new Error("获取订单失败");
        }
      } catch (error) {
        uni.showToast({
          title: error,
          icon: "error",
        });
      }
      uni.hideLoading();
    },

    showToastAndGoback(title) {
      uni.hideLoading();
      uni.showToast({
        title,
        icon: "error",
      });
    },

    // 支付
    async submitRemit() {
      const { radioParams, newPrice, CouponData, priceValue, oilGunNum, oilName } = this;
      if ((radioParams === "1" && newPrice > CouponData.balance) || priceValue < 0.01 || priceValue > 50000 || !oilGunNum || !oilName) {
        return;
      }
      const { openId, stationId } = this;
      const { ordNo } = this.CouponData;
      uni.showLoading({
        title: "加载中",
        mask: true,
      });
      if (this.radioParams === "2") {
        // 微信支付
        //根据接口返回的数据，在微信内拉起公众号支付，进行付款操作
        try {
          const response = await this.$Request({
            url: "/toThirdPayV2",
            method: "POST",
            data: {
              aliUserId: "1",
              newCouponFalg: "1",
              openId,
              payAppType: "1",
              ordNo,
              stationId,
            },
          });
          if (response.retCode === 0) {
            if (response.data.thirdPayment === "5") {
              uni.redirectTo({
                url: `/subPack/fuel/webview?url=${encodeURIComponent(JSON.stringify(response.data.redirectUrl))}`,
              });
            } else {
              const timeStamp = response.data.payTimeStamp;
              const nonceStr = response.data.paynonceStr;
              const payPackage = response.data.payPackage;
              const signType = response.data.paySignType;
              const paySign = response.data.paySign;

              // 填写微信的信息，启动支付
              if (!timeStamp || !nonceStr || !payPackage || !signType || !paySign) {
                this.showToastAndGoback("参数不完整~");
                return;
              }

              const [payErr, payData] = await uni.requestPayment({
                timeStamp: timeStamp,
                nonceStr: nonceStr,
                package: payPackage,
                signType: signType,
                paySign: paySign,
              });
              console.log("支付结果：", payErr, payData);
              if (!!payData && payData.errMsg === "requestPayment:ok") {
                uni.showToast({
                  title: "支付成功",
                  icon: "success",
                });
                uni.redirectTo({
                  url: `/subPack/fuel/success?ordNo=${ordNo}`,
                });
                return;
              }
              if (payErr.errMsg === "requestPayment:fail cancel") {
                console.log("用户取消支付");
                this.showToastAndGoback("用户取消了支付");
                this.onCancel(); // 取消支付语音播报
                return;
              }
              this.showToastAndGoback("支付失败");
              return;
            }
          } else {
            this.showToastAndGoback("获取订单失败~");
            throw new Error("获取订单失败");
          }
        } catch (error) {
          this.showToastAndGoback(error);
        }
      } else if (this.radioParams === "1") {
        // 电子卡支付
        try {
          const res = await this.$Request({
            url: "/newDzkCouponPaySetV3",
            method: "GET",
            data: { ordNo },
          });
          if (res.retCode !== 0) {
            this.showToastAndGoback("支付失败~");
            throw new Error("获取油站失败");
          } else {
            uni.showToast({
              title: "支付成功",
              icon: "success",
            });
            uni.redirectTo({
              url: `/subPack/fuel/success?ordNo=${ordNo}`,
            });
          }
        } catch (error) {
          this.showToastAndGoback(error);
        }
      } else {
        return;
      }
      uni.hideLoading();
    },

    // 取消支付播报
    async onCancel() {
      const params = {
        gunName: this.oilGunNum, // 枪号
        enterpriseId: this.enterpriseId,
        stationId: this.stationId,
        orderNo: this.CouponData.ordNo, // 订单号
        oilPersonId: this.userId, // 员工的userid
      };
      const res = await this.$Request({
        url: "/payOrder/cancel/broadcast",
        method: "get",
        data: params,
      });
      if (res && res.retCode != 0) {
        throw new Error(`${res && res.message}`);
      }
    },
  },
};
</script>

<style lang="scss">
.fuel_remit_wraper {
  box-sizing: border-box;
  min-height: 100vh;
  background: linear-gradient(to bottom, #f6bc8c, #f5f6f8, #f5f6f8, #f5f6f8);
  padding: 30rpx 20rpx 180rpx;

  .fuel_remit_nav {
    box-sizing: border-box;
    width: 100%;
    padding: 30rpx 20rpx 0;
    border-radius: 14rpx;
    background-color: #fff;
    overflow: hidden;
    margin-bottom: 26rpx;

    .title_wraper {
      display: flex;
      justify-content: space-between;

      .title_left {
        .title_name {
          font-weight: 700;
          font-size: 42rpx;
          margin-bottom: 10rpx;
        }

        .title_region {
          font-size: 24rpx;
        }
      }

      .title_right {
        display: flex;
        padding: 4rpx 16rpx;
        align-items: center;
        height: 28rpx;
        border-radius: 16rpx;
        background-color: #f5f5f5;

        .icon {
          width: 24rpx;
          height: 24rpx;
          margin-right: 4rpx;

          &.nav {
            background: url("../static/fuel/nav.png") no-repeat 0 0;
            background-size: 100% 100%;
          }
        }

        .text {
          font-size: 20rpx;
        }
      }
    }

    .main_wraper {
      display: flex;
      margin: 20rpx 0;

      .main_title {
        font-size: 46rpx;
        color: #ed6709;
        font-weight: 600;
        margin-right: 20rpx;

        .text {
          font-size: 28rpx;
        }
      }

      .main_station {
        font-size: 22rpx;
        color: #666;
        height: 40rpx;
        margin-top: 22rpx;
      }
    }

    .foolter_wraper {
      display: flex;

      .foolter_invoicing {
        border: 1px solid #d5d6d7;
        padding: 3rpx 6rpx;
        color: #7a7c7e;
        font-size: 16rpx;
        margin-right: 10rpx;
      }
    }
  }

  .all_coupon_wraper {
    box-sizing: border-box;
    width: 100%;
    padding: 30rpx 20rpx;
    border-radius: 14rpx;
    background-color: #fff;
    overflow: hidden;
    margin-bottom: 26rpx;

    .all_coupon {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;

      &.confirm {
        padding-bottom: 16rpx;
        border-bottom: 1px solid #f5f5f5;
      }

      .all_coupon_text {
        color: #000;
        font-weight: 600;
        font-size: 28rpx;
      }

      .all_coupon_val {
        color: #e1292c;
        font-size: 28rpx;
        font-weight: 600;
      }
    }

    .down_coupon {
      display: flex;
      justify-content: space-between;
      margin-bottom: 20rpx;

      .down_coupon_text {
        color: #000;
        font-weight: 600;
        font-size: 24rpx;
      }

      .down_coupon_val {
        color: #000;
        font-weight: 600;
        font-size: 26rpx;
      }
    }

    .coupon_info {
      position: relative;

      .coupon_info_main {
        display: flex;
        justify-content: space-between;
        padding-right: 30rpx;

        .coupon_left {
          color: #333;
          font-size: 24rpx;
        }

        .coupon_right {
          color: #666;
          font-size: 24rpx;
        }

        .icon_jiantou {
          position: absolute;
          top: 3rpx;
          right: 0rpx;
          width: 32rpx;
          height: 32rpx;
          background: url("../static/fuel/right.png") no-repeat 0 0;
          background-size: 100% 100%;
        }
      }
    }
  }

  .remit_page_container {
    box-sizing: border-box;
    width: 100%;
    padding: 28rpx 20rpx 20rpx;
    border-radius: 14rpx;
    background-color: #fff;
    overflow: hidden;
    margin-bottom: 26rpx;

    .remit_page_wraper {
      .remit_page_type {
        display: flex;
        justify-content: space-between;
        margin-bottom: 20rpx;
        padding-bottom: 16rpx;
        border-bottom: 1px solid #f5f5f5;
        color: #000;
        font-size: 28rpx;
        font-weight: 600;
      }

      .stored_radio {
        display: flex;
        justify-content: space-between;

        .stored_card {
          display: flex;
          align-items: center;
          font-size: 26rpx;
          font-weight: 600;
          color: #333;
          margin-left: 16rpx;

          .icon {
            width: 36rpx;
            height: 36rpx;
            margin-right: 16rpx;

            &.stored {
              background: url("../static/fuel/chuzhika.png") no-repeat 0 0;
              background-size: 100% 100%;
            }

            &.vx {
              background: url("../static/fuel/vx_remit.png") no-repeat 0 0;
              background-size: 100% 100%;
            }
          }
        }
      }

      .stored_amt {
        font-size: 24rpx;
        color: #999;
        padding: 20rpx;
        margin-left: 12rpx;
      }

      .divider_line {
        width: 100%;
        height: 1px;
        margin: 16rpx 0;
        background-color: #eee;
      }
    }
  }

  .bottom_fix_bar {
    height: 100rpx;
    z-index: 1;
    left: 0;
    width: 100%;
    position: fixed;
    bottom: 0;
    background-color: #fff;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .button_submit {
      line-height: 100rpx;
      text-align: center;
      width: 240rpx;
      height: 100%;
      font-size: 36rpx;
      background-color: #fb6703;
      color: #fff;

      &.active_button {
        background-color: #fafafa;
        color: #ccc;
      }
    }

    .car_container {
      position: relative;
      display: flex;
      align-items: center;
      flex: 1;

      .num {
        position: absolute;
        top: -10rpx;
        right: -5px;
        background-color: #32af51;
        border-radius: 50%;
        width: 20rpx;
        text-align: center;
        height: 20rpx;
        font-size: 16rpx;
        color: #fff;
      }

      .price_bar {
        .price_value {
          margin-left: 30rpx;
          font-size: 36rpx;
          font-weight: 600;
          color: #fb6703;
        }
      }

      .price_coupon {
        font-size: 22rpx;
        margin-left: 30rpx;

        .coupon_value {
          color: #fb6703;
        }
      }
    }
  }

  .coupons_popup_container {
    height: 80vh;
    position: relative;

    .icon_coupons {
      position: absolute;
      right: 26rpx;
      top: 26rpx;
      width: 48rpx;
      height: 48rpx;
      background: url("../static/icon/6_d05_close.2x.png") no-repeat 0 0;
      background-size: 100% 100%;
    }

    .title {
      width: 100%;
      text-align: center;
      height: 110rpx;
      line-height: 110rpx;
      font-size: 36rpx;
      font-weight: 600;
    }

    .van_popup_main {
      .popup_list {
        box-sizing: border-box;
        padding: 30rpx;
        margin: 30rpx;
        background-color: #f5f6f7;
        border-radius: 16rpx;
        display: flex;

        .left_popup {
          display: flex;
          flex-direction: column;
          justify-content: center;
          align-items: center;
          width: 220rpx;
          height: 170rpx;
          background: url("../static/coupon/quan1.2x.png") no-repeat 0 0;
          background-size: 100% 100%;
          color: #fff;
          margin-right: 16rpx;

          .valueDesc {
            font-size: 40rpx;
            margin-bottom: 32rpx;
          }

          .condition {
            font-size: 28rpx;
          }

          &.red {
            background: url("../static/coupon/quan2.2x.png") no-repeat 0 0;
            background-size: 100% 100%;
          }
        }

        .right_popup {
          display: flex;
          flex-direction: column;
          justify-content: space-between;

          .name {
            width: 150rpx;
            text-align: center;
            color: #333;
            font-size: 28rpx;
            height: 60rpx;
            line-height: 60rpx;
            background-color: #fad25e;
            border-radius: 60rpx;

            &.red {
              background-color: #ed9381;
            }
          }

          .title {
          }
        }

        .radio {
          position: absolute;
          right: 32rpx;

          input {
            zoom: 1.5;
          }
        }
      }
    }
  }
}
</style>
